module.exports = Room

var math = require('../helper/math')

function Room(peopleNum, roomManager) {
    this.max = peopleNum
    this.peoples = [] //Some params necessary: id,name,avatar,ready
    this.roomNum = -1
    this.roomManager = roomManager
    this.results = []//得出结果之后应该立即清零
}

Room.prototype.getInfo = function () {
    var result = {}

    result.max = this.max
    result.peoples = this.peoples
    if (this.results.length > 0) {
        result.results = this.results
        this.results = []
    }
    result.roomNum = this.roomNum

    return result
}
Room.prototype.exit = function (id) {
    for (var i = 0; i < this.peoples.length; i++) {
        var people = this.peoples[i]

        //TODO: Check people by id
        if (people.id == id) {
            this.peoples.splice(i, 1)
            this.checkRoomClose()
            return
        }
    }
}
Room.prototype.checkRoomClose = function () {
    if (this.peoples.length < 1) {
        if (this.roomManager) {
            console.log('Close room: ' + this.roomNum)
            this.roomManager.closeRoom(this.roomNum)
        }
    }
}
Room.prototype.ready = function (sid) {
    for (var people of this.peoples) {
        if (people.id == sid)
            people.ready = true
    }

    this.checkAllReady()
}
Room.prototype.unReady = function (sid) {
    for (var people of this.peoples) {
        if (people.id == sid)
            people.ready = false
    }
}
Room.prototype.enter = function (people) {
    if (this.peoples.length >= this.max)
        return false

    people.ready = false
    this.peoples.push(people)
    return true
}
Room.prototype.checkAllReady = function () {
    var allReady = true
    for (var people of this.peoples) {
        if (!people.ready) {
            allReady = false
            break
        }
    }

    if (!allReady)
        return

    this.gameStart()
}
Room.prototype.gameStart = function () {
    console.log('Game start')

    var results = []
    var srcNums = []

    for (var i = 1; i <= this.peoples.length; i++) {
        srcNums.push(i)
    }

    for (var people of this.peoples) {
        var index = math.getRandomInt(0, srcNums.length - 1)
        var result = (srcNums.splice(index, 1))[0]
        results.push({
            data: result
        })
    }

    console.log('Get results: ' + JSON.stringify(results))

    this.results = results
}